package com.sinopec.basemodule.widget.myedittext.clean

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import java.util.*


/**
 * 类描述：托盘编码输入框 2位一格<br/>
 * 创建人：吴冬冬<br/>
 * 创建时间：2020/4/13 10:49 <br/>
 */
class TaryCodeEditText : CleanEditText {
    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : super(
            context,
            attrs
    )

    constructor(
            context: Context,
            attrs: AttributeSet?,
            defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr)

    private val inputRule = " "

    init {
        initEt()
    }

    interface EtTextWatcher {
        fun onTextChanged(str: String)
    }

    fun setTextChangedListener(textWatcher: EtTextWatcher) {
        mEtTextWatcher = textWatcher
    }

    private var mEtTextWatcher: EtTextWatcher? = null

    fun getString(): String {
        return text.toString().replace(inputRule, "")
    }

    private fun initEt() {
        val beforeSb = StringBuilder()
        val textWatch = object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                beforeSb.clear()
                beforeSb.append(s.toString())
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
//                Log.d(
//                        "123===",
//                        "text=${text}--start=${start}--before=${before}--count=${count}"
//                )
                if (s == null) return
                if (s.toString().isEmpty()) {
                    callback()
                    return
                }

                var newStr = s.toString().replace(inputRule, "")
                //编码只能输入数字、大写英文
                val regex = "[\\dA-Fa-f]+".toRegex()
                if (!newStr.matches(regex)) {
                    //设置为原来的数值
                    removeTextChangedListener(this)
                    text?.apply {
                        replace(0, length, beforeSb.toString())
                    }
                    setSelection(beforeSb.toString().length)
                    addTextChangedListener(this)
                    callback()
                    return
                }
                val ownerPropertyRuler = "^.*[a-f]+.*$"
                var isUpperCase = false
                if (newStr.matches(ownerPropertyRuler.toRegex())) {
                    newStr = newStr.toUpperCase(Locale.CHINA)
                    isUpperCase = true
                }

                //是否在中间输入
                val isMiddleInput = (start + count) < s.length
//                Log.d(
//                    "123===",
//                    "是否在中间输入=${isMiddleInput}"
//                )
                //是否在末尾加入空客
                var isNeedAddSpace = false
                if ((!isMiddleInput && s.isNotEmpty() && s.length % 3 == 0)
                        || s.toString().startsWith(" ")
                        || s.toString().endsWith(" ")
                        || s.toString().contains(" {2,}".toRegex())) {
                    isNeedAddSpace = true
                }
//                Log.d(
//                    "123===",
//                    "是否末尾需要添加空格=${isNeedEndAddSpace}"
//                )

                if (isMiddleInput || isNeedAddSpace) {
                    val sb = getAddSpaceEditTextStrSb(newStr)
                    removeTextChangedListener(this)
                    text?.apply {
                        replace (0, length, sb.toString())
                    }
//                    Log.d(
//                            "123===",
//                            "text=${text}"
//                    )
                    if (!isMiddleInput) {
                        //如果在末尾的话，设置指针在末尾
                        setSelection(text!!.length)
                    } else if (isMiddleInput) {
                        if (before > count) {
                            //删除情况
                            val index = start /*- before + before*///剪切特殊情况
                            val newIndex =
                                    if (index < 0) 0 else if (index > text!!.length) text!!.length else index
                            setSelection(newIndex)
                        } else {
                            //增加时，如果光标在空格前，光标移动到添加数字后
                            if ((start - before + count) % 3 == 0) {
                                setSelection(if ((start + count - before + 1) < text!!.length) (start + count - before + 1) else text!!.length)
                            } else {
                                setSelection(start + count - before)
                            }
                        }
                    }
                    addTextChangedListener(this)
                }else if(isUpperCase){
                    val sb = getAddSpaceEditTextStrSb(newStr)
                    removeTextChangedListener(this)
                    text?.apply {
                        replace (0, length, sb.toString())
                    }
                    setSelection(text!!.length)
                    addTextChangedListener(this)
                }
                callback()
            }
        }
        addTextChangedListener(textWatch)
    }

    private fun getAddSpaceEditTextStrSb(newStr: String): StringBuilder {
        val sb = StringBuilder()
        for (i in newStr.indices step 2) {
            if (i + 2 <= newStr.length) {
                sb.append(newStr.substring(i, i + 2))
            } else {
                sb.append(newStr.substring(i, newStr.length))
            }
            //最后一个不添加空格
            if (newStr.length - 1 == i || newStr.length - 2 == i) {
                break
            }
            sb.append(inputRule)
        }
        return sb
    }

    //回调数据
    private fun callback() {
        mEtTextWatcher?.onTextChanged(text.toString())
    }
}